//@include "Model.jsx"
function saveAsPSD(filePath) {
    try {
        var d = new ActionDescriptor();
        var d1 = new ActionDescriptor();
        d.putObject(stringIDToTypeID("as"), stringIDToTypeID("photoshop35Format"), d1);
        d.putPath(stringIDToTypeID("in"), new File(filePath));
        d.putInteger(stringIDToTypeID("documentID"), 64);
        d.putBoolean(stringIDToTypeID("copy"), true);
        d.putBoolean(stringIDToTypeID("lowerCase"), true);
        d.putEnumerated(stringIDToTypeID("saveStage"), stringIDToTypeID("saveStageType"), stringIDToTypeID("saveSucceeded"));
        executeAction(stringIDToTypeID("save"), d, DialogModes.NO);

        var message = "已经保存{}至:" + filePath
        var inform = message.replace("{}", getCapitalizeWords("psd"))
        inform = decodeURI(inform)
        return inform
    } catch (e) {
        if (e.number != 8007) {
            alert("Line: " + e.line + "\n\n" + e, "Bug!", true);
            throw (e);
        }
    }
}

function saveAsJPEG(selectedID,filePath, wmName, quality) {
    try {
        var wmName = wmName || ""
        quality = quality || 12

        if (wmName != "") {
            // alert("水印")
            addWaterMark(selectedID);
        }
        // 生成完整的保存路径
        var saveFile = new File(filePath);


        var d = new ActionDescriptor();
        var d1 = new ActionDescriptor();
        d1.putInteger(stringIDToTypeID("extendedQuality"), quality);
        d1.putEnumerated(stringIDToTypeID("matteColor"), stringIDToTypeID("matteColor"), stringIDToTypeID("none"));
        d.putObject(stringIDToTypeID("as"), stringIDToTypeID("JPEG"), d1);
        d.putPath(stringIDToTypeID("in"), new File(saveFile));
        d.putInteger(stringIDToTypeID("documentID"), 74);
        d.putBoolean(stringIDToTypeID("copy"), true);
        d.putBoolean(stringIDToTypeID("lowerCase"), true);
        d.putEnumerated(stringIDToTypeID("saveStage"), stringIDToTypeID("saveStageType"), stringIDToTypeID("saveSucceeded"));
        executeAction(stringIDToTypeID("save"), d, DialogModes.NO);

        var message = "已经保存{}{}至:" + filePath
        var inform = message.replace("{}", getCapitalizeWords("jpg")).replace("{}", wmName)
        inform = decodeURI(inform)
        if (wmName != "") {
            deleteCurrentLayer();
        }
        return inform
    } catch (e) {
        if (e.number != 8007) {
            alert("Line: " + e.line + "\n\n" + e, "Bug!", true);
            throw (e);
        }
    }
}

function saveAsPNG(filePath, wmName) {
    try {
        var wmName = wmName || ""
        if (wmName != "") {
            addWaterMark(selectedID);
        }
        // 生成完整的保存路径
        var saveFile = new File(filePath);

        var d = new ActionDescriptor();
        var d1 = new ActionDescriptor();
        d1.putEnumerated(stringIDToTypeID("method"), stringIDToTypeID("PNGMethod"), stringIDToTypeID("quick"));
        d1.putEnumerated(stringIDToTypeID("PNGInterlaceType"), stringIDToTypeID("PNGInterlaceType"), stringIDToTypeID("PNGInterlaceNone"));
        d1.putEnumerated(stringIDToTypeID("PNGFilter"), stringIDToTypeID("PNGFilter"), stringIDToTypeID("PNGFilterAdaptive"));
        d1.putInteger(stringIDToTypeID("compression"), 0);
        d1.putEnumerated(stringIDToTypeID("embedIccProfileLastState"), stringIDToTypeID("embedOff"), stringIDToTypeID("embedOff"));
        d.putObject(stringIDToTypeID("as"), stringIDToTypeID("PNGFormat"), d1);
        d.putPath(stringIDToTypeID("in"), new File(saveFile));
        d.putInteger(stringIDToTypeID("documentID"), 74);
        d.putBoolean(stringIDToTypeID("copy"), true);
        d.putBoolean(stringIDToTypeID("lowerCase"), true);
        d.putBoolean(stringIDToTypeID("embedProfiles"), false);
        d.putEnumerated(stringIDToTypeID("saveStage"), stringIDToTypeID("saveStageType"), stringIDToTypeID("saveSucceeded"));
        executeAction(stringIDToTypeID("save"), d, DialogModes.NO);

        var message = "已经保存{}{}至:" + filePath
        var inform = message.replace("{}", getCapitalizeWords("png")).replace("{}", wmName)
        inform = decodeURI(inform)
        if (wmName != "") {
            deleteCurrentLayer();
        }

        return inform

    } catch (e) {
        if (e.number != 8007) {
            alert("Line: " + e.line + "\n\n" + e, "Bug!", true);
            throw (e);
        }
    }
}

function ProjectPath(ownFolderName) {
    var userSettings = loadDataFromFile()
    var dateFolder
    if (userSettings.isSaveDateFolder) {
        dateFolder = getOsSolidus() + getCurrentDat()
    } else {
        dateFolder = ""
    }
    if (userSettings.isSaveOwnFolder) {

        var path = userSettings["savePath"] + dateFolder + getOsSolidus()
        var pathOwn = path + ownFolderName
        $.writeln(ownFolderName)
        $.writeln(path)
        createFolder(ownFolderName, path)
        // $.writeln(path)
        updateSetting("alertInfo", userSettings["savePath"] + dateFolder)
        return path + ownFolderName

    } else {
        var path = userSettings["savePath"] + dateFolder
        //$.writeln(path)
        updateSetting("alertInfo", userSettings["savePath"] + dateFolder)
        var file = new File(path)
        $.writeln(file.path)
        $.writeln(file.name)
        createFolder(file.name, file.path)

        return path

    }


}

function ProjectName() {
    var userSettings = loadDataFromFile()
    if (userSettings.isUseCurrDocName) {
        var name = removeFileExtension(getCurrentDocumentName());
    } else {
        var name = getCurrentTime();
    }
    return name
}

function ProjectFormat(format) {
    var ProjectFormat = "." + format
    return ProjectFormat
}

function getFullSavePath(format, wmName) {
    format = format || ""
    wmName = wmName || ""
    counter = 1
    var sux = "_" + counter



    if (wmName != "") {
        wmName = "_" + wmName
        var baseName = ProjectPath(getCapitalizeWords(format) + wmName) + getOsSolidus() +
            ProjectName() + wmName + ProjectFormat(format)
        // $.writeln("bass:" + baseName)
        var file = new File(baseName); // 创建文件对象
        while (file.exists) {
            //alert("重名")
            // 如果文件存在，添加数字后缀
            file = new File(ProjectPath(getCapitalizeWords(format) + wmName) + getOsSolidus() +
                ProjectName() + sux + wmName + ProjectFormat(format));
            counter++;
        }

    } else {
        var baseName = ProjectPath(getCapitalizeWords(format)) + getOsSolidus() +
            ProjectName() + wmName + ProjectFormat(format)
        // $.writeln("bass:" + baseName)

        var file = new File(baseName); // 创建文件对象
        while (file.exists) {
            //alert("重名")
            // 如果文件存在，添加数字后缀
            file = new File(ProjectPath(getCapitalizeWords(format)) + getOsSolidus() +
                ProjectName() + "_" + counter + wmName + ProjectFormat(format));
            counter++;
        }
    }

    // var storageName = file.fullName
    // updateSetting("FullSavePath", decodeURI(storageName))

    var fullPath = file.fullName
    //$.writeln(fullPath)


    return decodeURI(fullPath)

}


function saveProject(selectedID) {
    //var userSettings = loadDataFromFile()
    // alert(selectedID)

    if (loadDataFromFile()["isSavePSD"]) {
        saveAsPSD(getFullSavePath("psd"))
    }
    if (loadDataFromFile()["isSaveJPG"]) {
        saveAsJPEG(selectedID,getFullSavePath("jpg"))
    }
    if (loadDataFromFile()["isSavePNG"]) {
        saveAsPNG(getFullSavePath("png"))
    }
    if (loadDataFromFile()["isSaveJPGW"]) {
        saveAsJPEG(selectedID,getFullSavePath("jpg", "水印"), "水印")
    }
    if (loadDataFromFile()["isSavePNGW"]) {
        saveAsPNG(getFullSavePath("png", "水印"), "水印")
    }
    if (loadDataFromFile()["isCloseDocument"]) {
        app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
    }
    if (loadDataFromFile().isAlert) {
        alert("已经保存至:" + decodeURI(loadDataFromFile().alertInfo))
    }
    if (loadDataFromFile().isExecute) {
        // 替换为你想要打开的文件夹的路径
        var specifiedFolderPath = loadDataFromFile().alertInfo;
        // 使用指定的路径创建 Folder 对象
        var specifiedFolder = new Folder(specifiedFolderPath);
        // 打开指定的文件夹
        specifiedFolder.execute();
    }


}


function addWaterMark(selectedID) {
    switch (selectedID) {
        case 0:
            selectedID = "5195d964-eee7-ff4c-aaae-0a1153e206bc";
            break;
        case 1:
            selectedID = "6790e1a4-00ff-b646-b8a0-3129c3eb35e7";
            break;
        case 2:
            selectedID = "7ffce5ee-ea22-374d-99fd-4f1f0935cf46";
            break;
    }
    

    adw(encodeChineseToURL(getPath().scriptFolderPath));
    ///////////////////////////////////////////////////////////////////////////////
    (function make_01544668152928() //填充图案
        {
            try {
                var d = new ActionDescriptor();
                var r = new ActionReference();
                r.putClass(stringIDToTypeID("contentLayer"));
                d.putReference(stringIDToTypeID("null"), r);
                var d1 = new ActionDescriptor();
                var d2 = new ActionDescriptor();
                var d3 = new ActionDescriptor();
                // d3.putString(stringIDToTypeID("name"), "Ë®Ó¡");
                d3.putString(stringIDToTypeID("ID"), selectedID);
                d2.putObject(stringIDToTypeID("pattern"), stringIDToTypeID("pattern"), d3);
                d1.putObject(stringIDToTypeID("type"), stringIDToTypeID("patternLayer"), d2);
                d.putObject(stringIDToTypeID("using"), stringIDToTypeID("contentLayer"), d1);
                executeAction(stringIDToTypeID("make"), d, DialogModes.NO);
            } catch (e) {
                if (e.number != 8007) {
                    alert("Line: " + e.line + "\n\n" + e, "Bug!", true);
                    throw (e);
                }
            }
        }
    )();

    ///////////////////////////////////////////////////////////////////////////////
    (function move_62383756646886() //置顶图案
        {
            try {
                var d = new ActionDescriptor();
                var r = new ActionReference();
                r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
                d.putReference(stringIDToTypeID("null"), r);
                var r1 = new ActionReference();
                r1.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("front"));
                d.putReference(stringIDToTypeID("to"), r1);
                executeAction(stringIDToTypeID("move"), d, DialogModes.NO);
            } catch (e) {
                if (e.number != 8007) {
                    alert("Line: " + e.line + "\n\n" + e, "Bug!", true);
                    throw (e);
                }
            }
        }
    )();

    ///////////////////////////////////////////////////////////////////////////////
    (function set_32701170351356() //透明度15%
        {
            try {
                var d = new ActionDescriptor();
                var r = new ActionReference();
                r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
                d.putReference(stringIDToTypeID("null"), r);
                var d1 = new ActionDescriptor();
                d1.putUnitDouble(stringIDToTypeID("opacity"), stringIDToTypeID("percentUnit"), 15);
                d.putObject(stringIDToTypeID("to"), stringIDToTypeID("layer"), d1);
                executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
            } catch (e) {
                if (e.number != 8007) {
                    alert("Line: " + e.line + "\n\n" + e, "Bug!", true);
                    throw (e);
                }
            }
        }
    )();

}
//导入水印
function adw(path) {
    //alert(encodeChineseToURL(path + getOsSolidus() + "watermark.pat"));
    ///////////////////////////////////////////////////////////////////////////////
    (function set_86533765075728() //
        {

            try {
                var d = new ActionDescriptor();
                var r = new ActionReference();
                r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("pattern"));
                r.putEnumerated(stringIDToTypeID("application"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
                d.putReference(stringIDToTypeID("null"), r);
                d.putPath(stringIDToTypeID("to"), new File(path + getOsSolidus() + "watermark.pat"));


                d.putBoolean(stringIDToTypeID("append"), true);
                executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
            } catch (e) {
                if (e.number != 8007) {
                    alert("Line: " + e.line + "\n\n" + e, "Bug!", true);
                    throw (e);
                }
            }
        }
    )();

}

//删除水印
function wsd() {

    try {
        var d = new ActionDescriptor();
        var r = new ActionReference();
        r.putIndex(stringIDToTypeID("pattern"), 14);
        d.putReference(stringIDToTypeID("null"), r);
        executeAction(stringIDToTypeID("delete"), d, DialogModes.NO);
    } catch (e) {
        if (e.number != 8007) {
            alert("Line: " + e.line + "\n\n" + e, "Bug!", true);
            throw (e);
        }
    }
}

function deleteCurrentLayer() {
    // 获取当前文档
    var currentDoc = app.activeDocument;

    // 检查是否有至少一个图层
    if (currentDoc.layers.length < 1) {
        alert("没有可删除的图层。");
        return;
    }

    // 获取当前图层
    var currentLayer = currentDoc.activeLayer;

    // 删除当前图层
    currentLayer.remove();
    wsd();
}